// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>,
}

impl ListNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        ListNode { next: None, val }
    }

    /// Creates a new linked list from a slice of values.
    pub fn from_slice(values: &[i32]) -> Option<Box<ListNode>> {
        let mut head = None;
        for &val in values.iter().rev() {
            let mut new_node = ListNode::new(val);
            new_node.next = head;
            head = Some(Box::new(new_node));
        }
        head
    }

    /// Converts the linked list into a Vec of values.
    pub fn to_vec(&self) -> Vec<i32> {
        let mut result = vec![];
        let mut current = Some(self);
        while let Some(node) = current {
            result.push(node.val);
            current = node.next.as_deref();
        }
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_list_conversion() {
        // 1. Test round trip: from_slice -> to_vec
        let values = vec![1, 2, 3, 4, 5];
        let list = ListNode::from_slice(&values).expect("from_slice should create a list");
        assert_eq!(list.to_vec(), values);

        // 2. Test empty slice
        let empty_values: Vec<i32> = vec![];
        let empty_list = ListNode::from_slice(&empty_values);
        assert!(empty_list.is_none());

        // 3. Test single element slice
        let single_value = vec![42];
        let single_list =
            ListNode::from_slice(&single_value).expect("from_slice should create a list");
        assert_eq!(single_list.to_vec(), single_value);
    }
}
